<!DOCTYPE HTML>
<html>
<head>
    <title>My WebSocket</title>
</head>

<body>
Welcome<br/>
<input id="text" type="text" /><button onclick="send()">Send</button>    <button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>

<script type="text/javascript">
    var websocket = null;

    if('WebSocket' in window){
        websocket = new WebSocket("ws://localhost/service");
    }
    else{
        alert('不支持')
    }

    websocket.onerror = function(){
        setMessageInnerHTML("error");
    };

    websocket.onopen = function(event){
        setMessageInnerHTML("open");
    }

    websocket.onmessage = function(event){
        setMessageInnerHTML(event.data);
    }

    websocket.onclose = function(){
        setMessageInnerHTML("close");
    }

    window.onbeforeunload = function(){
        websocket.close();
    }

    function setMessageInnerHTML(innerHTML){
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    function closeWebSocket(){
        websocket.close();
    }
    

    function send(){
        var message = document.getElementById('text').value;
	    var messageObj = {message:message,target:'target'};
	    var messageJson = JSON.stringify(messageObj);
        websocket.send(messageJson);
    }
</script>
</html>